package com.yb.bussiness.shoper;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.yb.base.dao.BaseDao;
import com.yb.base.dao.IBaseDao;
import com.yb.domain.VO.BrandType;
import com.yb.domain.VO.PingouVO;
import com.yb.domain.goods.TbrandAnnoucement;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.goods.TgCategory;
import com.yb.domain.goods.TpingouIndex;
import com.yb.domain.member.TsSysuser;
import com.yb.util.comm.DateTimeUtil;
import com.yb.util.framework.PageUtil;

public class BrandServiceImpl implements BrandService {
	private IBaseDao<TgBrand, Long> shopDao;
	private IBaseDao<TgCategory, Long> dao;
	private IBaseDao<PingouVO, Long> pgDao;
	private IBaseDao<TsSysuser, Long> tsDao;
	private IBaseDao<TbrandAnnoucement, Long> tbaDao;
	private IBaseDao<TpingouIndex, Long> tpiDao;
	private static final Logger LOGGER = Logger
			.getLogger(BrandServiceImpl.class);

	public BrandServiceImpl() {
		shopDao = new BaseDao<TgBrand, Long>(TgBrand.class);
		dao = new BaseDao<TgCategory, Long>(TgCategory.class);
		pgDao = new BaseDao<PingouVO, Long>(PingouVO.class);
		tsDao = new BaseDao<TsSysuser, Long>(TsSysuser.class);
		tbaDao = new BaseDao<TbrandAnnoucement, Long>(TbrandAnnoucement.class);
		tpiDao = new BaseDao<TpingouIndex, Long>(TpingouIndex.class);
	}

	/**
	 * 根据参数商家列表
	 */
	public List<TgBrand> findAllShoper(Map<String, String> parameMap) {
		try {
			String str = " SELECT b.* FROM t_g_brand b LEFT JOIN  t_s_sysuser t  ON  b.sysuserId= t.id WHERE b.realName is null  ";
			if (parameMap.get("name") != null
					&& !"".equals(parameMap.get("name"))) {
				str += "  and b.name LIKE   '%" + parameMap.get("name") + "%'";
			}
			if (parameMap.get("auding") != null
					&& !"".equals(parameMap.get("auding"))) {
				if ("0".equals(parameMap.get("auding")))
					str += "  and (b.auding = " + parameMap.get("auding")
							+ " or b.auding is null) ";
				else
					str += "  and b.auding = " + parameMap.get("auding");
			}
			if (parameMap.get("activityFlag") != null
                && !"".equals(parameMap.get("activityFlag"))) {
                    str += "  and b.activityFlag = " + parameMap.get("activityFlag");
            }
			if (parameMap.get("page") != null && parameMap.get("row") != null) {
				int start = Integer.parseInt(parameMap.get("page")) - 1;
				int limit = Integer.parseInt(parameMap.get("row"));
				str += " limit " + start * limit + "," + limit;
			}
			List<TgBrand> list = shopDao.findList(str);
			return list;
		} catch (Exception e) {
			LOGGER.error(" BrandServiceImpl findByParameMap error", e);
			return null;
		}
	}

	public List<TgBrand> findAllBrand() {
		try {
			String str = " SELECT t.name, t.imgsrc,t.id FROM t_brand_annoucement a,t_g_brand t where  a.brandId = t.id ORDER BY a.weights desc LIMIT 0,30  ";

			List<TgBrand> list = shopDao.findList(str);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(" BrandServiceImpl findAllBrand error", e);
			return null;
		}
	}

	/**
	 * 论坛页面 展示商家列表
	 */
	public PageUtil findAllShoperTOJulebu(Map<String, String> parameMap) {
		PageUtil pu = new PageUtil();
		String sql = "SELECT COUNT(B.ID) FROM T_G_BRAND B LEFT JOIN T_S_SYSUSER T ON B.SYSUSERID= T.ID WHERE T.TYPE=2";
		try {
			int total = Integer
					.parseInt((dao.findObjectArryList(sql).get(0))[0]
							.toString());
			pu.setTotalRecords(total);
		} catch (NumberFormatException e) {
			pu.setTotalRecords(0);
		}
		sql = "SELECT B.ID AS ID ,B.NAME AS NAME ,B.CODE AS CODE ,B.BRANDDESC AS BRANDDESC, B.CATEGORYID AS CATEGORYID , B.IMGSRC AS IMGSRC ,B.BRANDORDER AS BRANDORDER,B.BRANDPIC AS BRANDPIC ,B.SHOPADDRESS AS SHOPADDRESS , B.PHONE AS PHONE,B.COMPANYOPERER AS COMPANYOPERER, B.SYSUSERID AS SYSUSERID, B.AUDING AS AUDING ,B.ANNOUNCEMENT AS ANNOUNCEMENT, B.SEX AS SEX, B.TEL AS TEL, B.COMPANYNAME AS COMPANYNAME, B.REALNAME  AS REALNAME FROM T_G_BRAND B LEFT JOIN  T_S_SYSUSER T  ON  B.SYSUSERID= T.ID WHERE T.TYPE=2 LIMIT ?,?";
		int start = Integer.parseInt(parameMap.get("start"));
		int limit = Integer.parseInt(parameMap.get("limit"));
		List<TgBrand> list = shopDao.findList(sql, new Object[] {
				(start - 1) * limit, limit });
		pu.setList(list);
		pu.setPageNo(start);
		pu.setPageSize(limit);
		return pu;
	}

	/**
	 * 根据id查找类别名称
	 * 
	 * @param id
	 * @return
	 */
	public TgCategory findCategory(int id) {
		try {
			String str = "select * from   t_g_category  where id=?";
			List<TgCategory> list = dao.findList(str, new Object[] { id });
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询总数
	 */
	public int count(Map<String, String> parameMap) {
		int count = 0;
		try {
			String str = "SELECT count(b.id) FROM t_g_brand b LEFT JOIN  t_s_sysuser t "+  
							"ON  b.sysuserId= t.id WHERE b.realName IS NULL    AND (b.auding = 0 OR b.auding IS NULL) ";
			if (parameMap.get("name") != null
					&& !"".equals(parameMap.get("name"))) {
				str += "  and b.name LIKE   '%" + parameMap.get("name") + "%'";
			}
			if (parameMap.get("auding") != null
					&& !"".equals(parameMap.get("auding"))) {
				if ("0".equals(parameMap.get("auding")))
					str += "  and (b.auding = " + parameMap.get("auding")
							+ " or b.auding is null) ";
				else
					str += "  and b.auding = " + parameMap.get("auding");
			}if (parameMap.get("activityFlag") != null
                && !"".equals(parameMap.get("activityFlag"))) {
                str += "  and b.activityFlag = " + parameMap.get("activityFlag");
			}
			List<Object[]> objAryList = shopDao.findObjectArryList(str);
			if (null != objAryList && objAryList.size() > 0) {
				Object[] obj = objAryList.get(0);
				count = new Integer(obj[0].toString());
			}
		} catch (Exception e) {
			LOGGER.error(" BrandServiceImpl  count error", e);
			return 0;
		}
		return count;
	}

	
	
	
	public boolean deleteById(String ids) {
		boolean isFlag = true;
		if ("".equals(ids))
			return false;
		String sql = "";
		String[] delteid = ids.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "delete  from t_g_brand where  id=" + delteid[i];
				TgBrand tg = findById(delteid[i]);
				if (tg != null) {
					tsDao.delete(" delete from  t_s_sysuser where id="
							+ tg.getSysuserId());
				}
				shopDao.delete(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(" BrandServiceImpl deleteById   error", e);
			return false;
		}
		return isFlag;
	}

	public boolean updateAutingId(String id, String autding) {
		try {
			String sql = " UPDATE  t_g_brand t set t.auding= " + autding
					+ " WHERE t.sysuserId= " + id;
			shopDao.update(sql);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(" BrandServiceImpl updateAutingId   error", e);
			return false;
		}

	}
	
	public boolean changeActivity(String id, String activityFlag) {
        try {
            String sql = " UPDATE  t_g_brand t set t.activityFlag= " + activityFlag
                    + " WHERE t.id= " + id;
            shopDao.update(sql);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(" BrandServiceImpl changeActivity   error", e);
            return false;
        }

    }

	public TgBrand findById(String id) {
		return shopDao.read(new Long(id));
	}

	public TgBrand findByUserId(String userid) {
		String str = " SELECT * FROM   t_g_brand  WHERE sysuserId= ?   ";/*
																			 * AND
																			 * auding=1
																			 */
		try {
			List<TgBrand> list = shopDao.findList(str, new Object[] { userid });
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		} catch (Exception e) {
			LOGGER.error(
					" BrandServiceImpl  findByUserId " + userid + " error", e);
			return null;
		}

		return null;
	}

	public List<TgBrand> findByMarketId(Long id, int page, int limit) {
		String sql = "select * from t_g_brand tgb where EXISTS("
				+ "select 1 from t_market_brand tmb where marketId = ? and tmb.brandId = tgb.id) limit ?,?";
		return shopDao.findList(sql, new Object[] { id, (page - 1) * limit,
				limit });
	}

	public List<TgBrand> findByMarketIdNotIn(Long id, String categoryId,
			String keyword) {
		if (null == categoryId || "".equals(categoryId)) {
			String sql = "";
			if ("".equals(keyword))
				sql = "select * from t_g_brand tgb where tgb.name is not null and not EXISTS("
						+ "select 1 from t_market_brand tmb where marketId = ? and tmb.brandId = tgb.id)";
			else
				sql = "select * from t_g_brand tgb where tgb.name is not null and not EXISTS("
						+ "select 1 from t_market_brand tmb where marketId = ? and tmb.brandId = tgb.id) ";
			return shopDao.findList(sql, new Object[] { id });
		} else {
			String sql = "";
			if ("".equals(keyword))
				sql = "select * from "
						+ "(SELECT * FROM t_g_brand ttt WHERE EXISTS (SELECT 1 FROM t_brand_type tbt WHERE tbt.brandId = ttt.id AND  "
						+ "EXISTS (SELECT 1 FROM t_g_category tgc WHERE tgc.id = tbt.categoryId AND instr(',"+categoryId+",',CONCAT(',',tgc.pID,',')) <> 0))) "
						+ "tgb where tgb.name is not null and not EXISTS("
						+ "select 1 from t_market_brand tmb where marketId = "+id+" and tmb.brandId = tgb.id)";
			else
				sql = "select * from "
						+ "(SELECT * FROM t_g_brand ttt WHERE EXISTS (SELECT 1 FROM t_brand_type tbt WHERE tbt.brandId = ttt.id AND  "
						+ "EXISTS (SELECT 1 FROM t_g_category tgc WHERE tgc.id = tbt.categoryId AND instr('"+categoryId+"',CONCAT(',',tgc.pID,',')) <> 0))) "
						+ "tgb where tgb.name is not null and not EXISTS("
						+ "select 1 from t_market_brand tmb where marketId = "+id+" and tmb.brandId = tgb.id)";
			return shopDao.findList(sql);
		}
	}

	@SuppressWarnings("unchecked")
	public List<BrandType> findByBrandId(Long id) {
		List<BrandType> list = new ArrayList<BrandType>();
		String sql = "select distinct tbt.brandId brandId,tgc.id categoryId,tgc.name categoryName,tgcP.name typeName from t_brand_type tbt, t_g_category tgc, t_g_category tgcP where tbt.categoryId = tgc.id and tgcP.id = tgc.pid and tbt.brandId = ?";
		List<Map<String, Object>> mapList = shopDao.findMapList(sql,
				new Object[] { id });
		if (null != mapList)
			for (Iterator iterator = mapList.iterator(); iterator.hasNext();) {
				Map<String, Object> map = (Map<String, Object>) iterator.next();
				BrandType bt = new BrandType();
				bt.setBrandId(new Long(map.get("brandId").toString()));
				bt.setCategoryId(new Long(map.get("categoryId").toString()));
				bt.setCategoryName(map.get("categoryName").toString());
				bt.setTypeName(map.get("typeName").toString());
				list.add(bt);
			}
		return list;
	}

	public boolean saveOrUpdate(TgBrand brand) {
		try {
			shopDao.saveOrUpdate(brand);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public List<TgBrand> findBrandByCategoryId(Long categoryId) {
		if (null == categoryId)
			return new ArrayList<TgBrand>();
		String sql = "SELECT distinct b.* FROM t_g_brand b,t_brand_type t WHERE b.id = t.brandId AND t.categoryId = ?";
		return shopDao.findList(sql, new Object[] { categoryId });
	}

	public List<TgBrand> findBrandByTypeId(Long typeId) {
		String sql = "SELECT b.* FROM t_g_brand b,t_brand_type t WHERE b.id = t.brandId AND t.typeId = ?";
		return shopDao.findList(sql, new Object[] { typeId });
	}

	public Map<String, Object> findBrandByTypeAndCategroy(Long categoryId,
			Long typeId,Long bigCategory, int page, int limit,String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		String sql="", countSql="";
		Long id = 0l;
		boolean flag = true;
		if(typeId != 0l){
            sql = "SELECT  b.id,b.name,b.companyName,b.phone,t.weights auding,b.imgsrc,t.typeId,t.categoryId,CONCAT((SELECT tgc1.name FROM t_g_category tgc1 WHERE id = (SELECT tgc2.pid FROM t_g_category tgc2 WHERE tgc2.id = t.categoryId)),'-',(SELECT tgc.name FROM t_g_category tgc WHERE tgc.id = t.categoryId),IFNULL((SELECT CONCAT('-',tgt.name) FROM t_g_type tgt WHERE tgt.id = t.typeId),'')) accTitle FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId AND t.typeId = "+typeId+" and b.name like '%"+name+"%'  order by t.weights desc limit ?,?";
            countSql = "select count(DISTINCT b.id) FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId AND t.typeId = "+typeId+" and b.name like '%"+name+"%' ";
            flag = false;
		}
		if(flag&&categoryId!=0l){
		    sql = "SELECT  b.id,b.name,b.companyName,b.phone,t.weights auding,b.imgsrc,t.typeId,t.categoryId,CONCAT((SELECT tgc1.name FROM t_g_category tgc1 WHERE id = (SELECT tgc2.pid FROM t_g_category tgc2 WHERE tgc2.id = t.categoryId)),'-',(SELECT tgc.name FROM t_g_category tgc WHERE tgc.id = t.categoryId),IFNULL((SELECT CONCAT('-',tgt.name) FROM t_g_type tgt WHERE tgt.id = t.typeId),'')) accTitle FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId AND t.categoryId = "+categoryId+" and b.name like '%"+name+"%' order by t.weights desc limit ?,?";
            countSql = "select count( b.id) FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId  AND t.categoryId = "+categoryId+" and b.name like '%"+name+"%' ";
            flag = false;
		}if(flag&&bigCategory!=0l){
		    sql = "SELECT  b.id,b.name,b.companyName,b.phone,t.weights auding,b.imgsrc,t.typeId,t.categoryId,CONCAT((SELECT tgc1.name FROM t_g_category tgc1 WHERE id = (SELECT tgc2.pid FROM t_g_category tgc2 WHERE tgc2.id = t.categoryId)),'-',(SELECT tgc.name FROM t_g_category tgc WHERE tgc.id = t.categoryId),IFNULL((SELECT CONCAT('-',tgt.name) FROM t_g_type tgt WHERE tgt.id = t.typeId),'')) accTitle FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId AND t.categoryId in (select id from t_g_category where  pID = "+bigCategory+") and b.name like '%"+name+"%' order by t.weights desc limit ?,?";
            countSql = "select count( b.id) FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId  AND t.categoryId  in (select id from t_g_category where  pID = "+bigCategory+") and b.name like '%"+name+"%' ";
            flag = false;
		}if(flag){
		    sql = "SELECT  b.id,b.name,b.companyName,b.phone,t.weights auding,b.imgsrc,t.typeId,t.categoryId,CONCAT((SELECT tgc1.name FROM t_g_category tgc1 WHERE id = (SELECT tgc2.pid FROM t_g_category tgc2 WHERE tgc2.id = t.categoryId)),'-',(SELECT tgc.name FROM t_g_category tgc WHERE tgc.id = t.categoryId),IFNULL((SELECT CONCAT('-',tgt.name) FROM t_g_type tgt WHERE tgt.id = t.typeId),'')) accTitle  FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId  and b.name like '%"+name+"%' order by t.weights desc limit ?,?";
            countSql = "select count( b.id) FROM t_g_brand b,t_pinggou t WHERE b.id = t.brandId  and b.name like '%"+name+"%' ";
		}
		
		List<Object[]> objAryList = shopDao.findObjectArryList(countSql,
				new Object[] {});
		List<TgBrand> list = new ArrayList<TgBrand>();
		Object[] obj = objAryList.get(0);
		map.put("count", obj[0].toString());
		if (!"0".equals(obj[0].toString())) {
			list = shopDao.findList(sql, new Object[] { (page - 1) * limit,
					limit });
		}
		map.put("data", list);
		return map;
	}

	public List<TgBrand> findHotBrand(int start, int limit) {
		String sql = "select * from t_g_brand t where exists ( "
				+ "select 1 from ( "
				+ "select brandId from t_g_brand_member group by brandId order by count(*) desc limit ?,? "
				+ ") temp where t.id = temp.brandId)";
		return shopDao.findList(sql, new Object[] { start, limit });
	}

	/*(SELECT * FROM t_p_buy_record tpbr1 WHERE tpbr1.autding = '1')*/
	@SuppressWarnings("static-access")
	public List<PingouVO> findPingouList(Long categoryId, int start, int limit) {
		int year = DateTimeUtil.getIntYear();
		Calendar ca = Calendar.getInstance();
		int month = ca.get(Calendar.MONTH) + 1;
		int[] queryMonth = bulidMonthAry(month);
		StringBuffer sql = new StringBuffer();
		sql
				.append("SELECT tt.*,IFNULL(tgb.imgsrc,'fileFloder/brand.jpg') AS imgSrc,tgb.activityFlag FROM (");
		sql.append("SELECT temp.brandId,temp.categoryId,weights");
		for (int i = 0; i < queryMonth.length; i++) {
			sql.append(",");
			int temp = queryMonth[i];
			int year_temp = year;
			if (temp > 12) {
				temp = temp - 12;
				year_temp = year_temp + 1;
			}
			String temp_month = (temp + "").length() == 1 ? "0" + temp : ""
					+ temp;
			sql.append(" IFNULL(sum(if(MONTH(partTime)='" + temp_month
					+ "' and YEAR(partTime)='" + year_temp
					+ "',1,0)),0) as count" + (i + 1));
		}
		sql
				.append(",IFNULL(sum(if(partTime is null,0,1)),0) as countAll FROM ( SELECT tpg.brandId brandId,tbr.partTime partTime,tbr.autding,tbr.name,tpg.categoryId ,tpg.weights,tbr.userId ");

		sql
				.append(" FROM (SELECT tpp.* FROM (select ttt.id,ttt.brandId,ttt.typeId,ttt.categoryId,tpi.weights weights from t_pinggou ttt,t_pingou_index tpi where ttt.id = tpi.pingouId) tpp WHERE EXISTS (SELECT 1 FROM t_g_category tgc WHERE tgc.id = tpp.categoryId AND tgc.pid = ?)) tpg LEFT JOIN t_p_buy_record tbr ON tpg.brandId = tbr.brandId AND tbr.userid!=0 ORDER BY tpg.brandId ");
		sql
				.append(" ) temp GROUP BY brandId ) tt, (select * from t_g_brand where auding = '1') tgb WHERE tt.brandId = tgb.id");
		// sql.append("order by IFNULL(sum(if(MONTH(partTime)='" + month
		// + "' and YEAR(partTime)='" + year + "',1,0)),0) desc");
		sql.append(" order by tt.weights desc");
		// countSql.append("group by temp.id ");
		sql.append(" limit ?,?");
		List<PingouVO> list = pgDao.findList(sql.toString(), new Object[] {
				categoryId, start, limit });
		return list;
	}

	public PageUtil findAllShoperBy(Map<String, String> parameMap) {
		try {
			String str = " SELECT  b.* FROM t_g_brand b LEFT JOIN  t_s_sysuser t  ON  b.sysuserId= t.id WHERE  t.type=2 ";
			if (parameMap.get("name") != null) {
				str += "  and b.name LIKE   '%" + parameMap.get("name") + "%'";
			}
			if (parameMap.get("page") != null && parameMap.get("limit") != null) {
				int start = Integer.parseInt(parameMap.get("page")) - 1;
				int limit = Integer.parseInt(parameMap.get("limit"));
				str += " limit " + start * limit + "," + limit;
			}
			List<TgBrand> list = shopDao.findList(str);
			int count = count1(parameMap);
			PageUtil pu = new PageUtil();
			pu.setList(list);
			pu.setPageNo(Integer.parseInt(parameMap.get("page")));
			pu.setPageSize(Integer.parseInt(parameMap.get("limit")));
			pu.setTotalRecords(count);
			return pu;
		} catch (Exception e) {
			LOGGER.error(" BrandServiceImpl findAllShoperBy error", e);
			return null;
		}
	}

	/**
	 * 查询总数
	 */
	public int count1(Map<String, String> parameMap) {
		int count = 0;
		try {
			String str = "  SELECT count(*) FROM t_g_brand b LEFT JOIN  t_s_sysuser t  ON  b.sysuserId= t.id WHERE t.type=2";
			if (parameMap.get("name") != null
					&& !"".equals(parameMap.get("name"))) {
				str += "  and b.name LIKE   '%" + parameMap.get("name") + "%'";
			}
			if (parameMap.get("auding") != null
					&& !"".equals(parameMap.get("auding"))) {
				str += "  and b.auding = " + parameMap.get("auding");
			} else {
				str += "  and b.auding = '1' ";
			}
			List<Object[]> objAryList = shopDao.findObjectArryList(str);
			if (null != objAryList && objAryList.size() > 0) {
				Object[] obj = objAryList.get(0);
				count = new Integer(obj[0].toString());
			}
		} catch (Exception e) {
			LOGGER.error(" BrandServiceImpl  count error", e);
			return 0;
		}
		return count;
	}

	private int[] bulidMonthAry(int month) {
		int[] temp = new int[12];
		for (int i = 0; i < 12; i++) {
			temp[i] = month + i;
		}
		return temp;
	}

	public List<TgBrand> findHotBrandByCategory(Long categoryId, int start,
			int limit) {
		String sql = "SELECT tgb.* FROM t_g_brand tgb,t_brand_category_hot tbch WHERE tgb.id = tbch.brandId AND tbch.categoryId = ? ORDER BY tbch.weights desc limit ?,?";
		return shopDao.findList(sql, new Object[] { categoryId, start, limit });
	}

	public List<TgBrand> findAncumentHotBrandByCategory(Long categoryId,
			int start, int limit) {
		String sql = "SELECT tgb.* FROM t_g_brand tgb,t_brand_annoucement tbch WHERE tgb.id = tbch.brandId AND tbch.categoryId = ? ORDER BY tbch.weights desc limit ?,?";
		return shopDao.findList(sql, new Object[] { categoryId, start, limit });
	}

	public TgBrand searchBySysId(int id) {
		return shopDao.uniqueResult(
				"SELECT * FROM  t_g_brand WHERE  sysuserId=?",
				new Object[] { id });
	}

	public PageUtil findBrandByCategoryIdOrTypeId(Long categoryId, Long typeId,
			int pageNo, int limit) {
		Long tempId;
		int year = DateTimeUtil.getIntYear();
		Calendar ca = Calendar.getInstance();
		int month = ca.get(Calendar.MONTH) + 1;
		int[] queryMonth = bulidMonthAry(month);
		StringBuffer sql = new StringBuffer();
		StringBuffer countSql = new StringBuffer();
		sql
				.append("SELECT tt.*,IFNULL(tgb.imgsrc,'fileFloder/brand.jpg') AS imgSrc,tgb.activityFlag FROM (");
		sql.append("SELECT temp.brandId,temp.categoryId,weights");
		for (int i = 0; i < queryMonth.length; i++) {
			sql.append(",");
			int temp = queryMonth[i];
			int year_temp = year;
			if (temp > 12) {
				temp = temp - 12;
				year_temp = year_temp + 1;
			}
			String temp_month = (temp + "").length() == 1 ? "0" + temp : ""
					+ temp;
			sql.append(" IFNULL(sum(if(MONTH(partTime)='" + temp_month
					+ "' and YEAR(partTime)='" + year_temp
					+ "',1,0)),0) as count" + (i + 1));
		}
		sql
				.append(",IFNULL(sum(if(partTime is null,0,1)),0) as countAll FROM ( SELECT tpg.brandId brandId,tbr.partTime partTime,tbr.autding,tbr.name,tpg.categoryId ,tpg.weights,tbr.userId  ");

		if (null != typeId && typeId > 0l) {
			tempId = typeId;
			sql
					.append(" FROM (SELECT * FROM t_pinggou p WHERE p.typeId = ? GROUP BY p.brandId ORDER BY p.weights DESC) tpg LEFT JOIN t_p_buy_record  tbr ON tpg.brandId = tbr.brandId AND tbr.userid!=0 ORDER BY tpg.brandId ");
		} else {
			tempId = categoryId;
			sql
					.append(" FROM (SELECT * FROM t_pinggou p WHERE p.categoryId = ? GROUP BY p.brandId ORDER BY p.weights DESC) tpg LEFT JOIN t_p_buy_record tbr ON tpg.brandId = tbr.brandId AND tbr.userid!=0 ORDER BY tpg.brandId ");
		}
		sql
				.append(" ) temp GROUP BY brandId ) tt, (select * from t_g_brand where auding = '1') tgb WHERE tt.brandId = tgb.id");
		// sql.append("order by IFNULL(sum(if(MONTH(partTime)='" + month
		// + "' and YEAR(partTime)='" + year + "',1,0)),0) desc");
		sql.append(" order by tt.weights desc");
		// countSql.append("group by temp.id ");
		countSql.append(sql);
		sql.append(" limit ?,?");
		List<PingouVO> brandList = pgDao.findList(sql.toString(), new Object[] {
				tempId, (pageNo - 1) * limit, limit });
		PageUtil pu = new PageUtil();
		pu.setList(brandList);
		pu.setPageNo(pageNo);
		pu.setPageSize(limit);
		List<PingouVO> countList = pgDao.findList(countSql.toString(),
				new Object[] { tempId });
		if (null != countList && countList.size() > 0) {
			pu.setTotalRecords(new Integer(countList.size()));
		} else {
			pu.setTotalRecords(0);
		}
		return pu;
	}

	public PageUtil findBrandByCategoryIdOrTypeId(Long categoryId, Long typeId,
			int pageNo, int limit, Long marketId) {
		Long tempId;
		int year = DateTimeUtil.getIntYear();
		Calendar ca = Calendar.getInstance();
		int month = ca.get(Calendar.MONTH) + 1;
		int[] queryMonth = bulidMonthAry(month);
		StringBuffer sql = new StringBuffer();
		StringBuffer countSql = new StringBuffer();
		sql
				.append("SELECT tt.*,IFNULL(tgb.imgsrc,'fileFloder/brand.jpg') AS imgSrc,tgb.activityFlag FROM (");
		sql.append("SELECT temp.brandId,temp.categoryId,weights");
		for (int i = 0; i < queryMonth.length; i++) {
			sql.append(",");
			int temp = queryMonth[i];
			int year_temp = year;
			if (temp > 12) {
				temp = temp - 12;
				year_temp = year_temp + 1;
			}
			String temp_month = (temp + "").length() == 1 ? "0" + temp : ""
					+ temp;
			sql.append(" IFNULL(sum(if(MONTH(partTime)='" + temp_month
					+ "' and YEAR(partTime)='" + year_temp
					+ "',1,0)),0) as count" + (i + 1));
		}
		sql
				.append(",IFNULL(sum(if(partTime is null,0,1)),0) as countAll FROM ( SELECT tpg.brandId brandId,tbr.partTime partTime,tbr.autding,tbr.name,tpg.categoryId ,tpg.weights,tbr.userId  ");

		if (null != typeId && typeId > 0l) {
			tempId = typeId;
			sql
					.append(" FROM (SELECT * FROM t_pinggou p WHERE p.typeId = ?  GROUP BY p.brandId ORDER BY p.weights DESC) tpg LEFT JOIN t_p_buy_record tbr ON tpg.brandId = tbr.brandId AND tbr.userid!=0 ORDER BY tpg.brandId ");
		} else {
			tempId = categoryId;
			sql
					.append(" FROM (SELECT * FROM t_pinggou p  WHERE p.categoryId = ?  GROUP BY p.brandId ORDER BY p.weights DESC) tpg LEFT JOIN t_p_buy_record tbr ON tpg.brandId = tbr.brandId AND tbr.userid!=0 ORDER BY tpg.brandId ");
		}
		sql
				.append(" ) temp GROUP BY brandId ) tt, (select * from t_g_brand where auding = '1') tgb,t_market_brand tmb WHERE tt.brandId = tgb.id AND tmb.marketId = ? AND tmb.brandId = tt.brandId");
		// sql.append("order by IFNULL(sum(if(MONTH(partTime)='" + month
		// + "' and YEAR(partTime)='" + year + "',1,0)),0) desc");
		sql.append(" order by tt.weights desc");
		// countSql.append("group by temp.id ");
		countSql.append(sql);
		sql.append(" limit ?,?");
		List<PingouVO> brandList = pgDao.findList(sql.toString(), new Object[] {
				tempId, marketId, (pageNo - 1) * limit, limit });
		PageUtil pu = new PageUtil();
		pu.setList(brandList);
		pu.setPageNo(pageNo);
		pu.setPageSize(limit);
		List<PingouVO> countList = pgDao.findList(countSql.toString(),
				new Object[] { tempId, marketId });
		if (null != countList && countList.size() > 0) {
			pu.setTotalRecords(countList.size());
		} else {
			pu.setTotalRecords(0);
		}
		return pu;
	}

	public Integer findPingouCount(Long brandId, Long categoryId, Long typeId) {
		Integer count = 0;
		if (null != brandId) {
			StringBuffer sql = new StringBuffer();
			sql
					.append("select count(*) from t_p_buy_record tbr where tbr.brandId = ? and EXISTS (SELECT 1 FROM t_pinggou tp WHERE tp.brandId = tbr.brandId ");
			Long tempId;
			if (null != typeId && typeId > 0l) {
				tempId = typeId;
				sql.append("and tbr.typeId = ?) and tbr.autding = '1' ");
			} else {
				tempId = categoryId;
				sql.append("and tbr.categoryId = ? ) and tbr.autding = '1'");
			}
			List<Object[]> countList = shopDao.findObjectArryList(sql
					.toString(), new Object[] { brandId, tempId });
			if (null != countList && countList.size() > 0) {
				Object[] countAry = countList.get(0);
				count = new Integer(countAry[0].toString());
			}
		} else {
			StringBuffer sql = new StringBuffer();
			sql
					.append("select count(*) from t_p_buy_record tbr WHERE EXISTS (SELECT 1 FROM t_pinggou tp WHERE tp.brandId = tbr.brandId and ");
			Long tempId;
			if (null != typeId && typeId > 0l) {
				tempId = typeId;
				sql.append(" tp.typeId = ? ) and tbr.autding = '1'");
			} else {
				tempId = categoryId;
				sql.append(" tp.categoryId = ? ) and tbr.autding = '1'");
			}
			List<Object[]> countList = shopDao.findObjectArryList(sql
					.toString(), new Object[] { tempId });
			if (null != countList && countList.size() > 0) {
				Object[] countAry = countList.get(0);
				count = new Integer(countAry[0].toString());
			}
		}
		return count;
	}

	public Integer findTotalCount() {
		String pgCountSql = "select count(*) from t_p_buy_record";
		String pqCountSql = "select count(*) from t_g_brand_member";
		int pgCount = 0, pqCount = 0;
		List<Object[]> pgCountList = shopDao.findObjectArryList(pgCountSql);
		if (null != pgCountList && pgCountList.size() > 0) {
			Object[] countAry = pgCountList.get(0);
			pgCount = new Integer(countAry[0].toString());
		}
		List<Object[]> pqCountList = shopDao.findObjectArryList(pqCountSql);
		if (null != pqCountList && pqCountList.size() > 0) {
			Object[] countAry = pqCountList.get(0);
			pqCount = new Integer(countAry[0].toString());
		}
		return pgCount + pqCount;
	}

	public List<TgBrand> findBrandByCategroyId(Long categoryId) {
		String sql = "select tgb.name,tgb.imgsrc,tgb.id,tbch.weights as auding from t_g_brand tgb,t_brand_category_hot tbch where tbch.brandId = tgb.id and tbch.categoryId = ? order by tbch.weights desc";
		return shopDao.findList(sql, new Object[] { categoryId });
	}

	public List<TgBrand> findBrandByAnnocumentCategroyId(Long categoryId) {
		String sql = "select tgb.name,tgb.imgsrc,tgb.id,tbch.weights as auding from t_g_brand tgb,t_brand_annoucement tbch where tbch.brandId = tgb.id and tbch.categoryId = ? order by tbch.weights desc";
		return shopDao.findList(sql, new Object[] { categoryId });
	}

	public void deleteBrandHot(Long categoryId, Long brandId) {
		String sql = "delete from t_brand_category_hot where brandId = ? and categoryId = ?";
		shopDao.delete(sql, new Object[] { brandId, categoryId });
	}

	public void deleteancumentBrandHot(Long categoryId, Long brandId) {
		String sql = "delete from t_brand_annoucement where brandId = ? and categoryId = ?";
		shopDao.delete(sql, new Object[] { brandId, categoryId });
	}

	public void deleteancumentBrandHot(Long cid) {
		String sql = "delete from t_brand_annoucement where id = ? ";
		shopDao.delete(sql, new Object[] { cid });
	}

	public void updateBrandHot(Long categoryId, Long brandId, Integer weights) {
		String sql = "update t_brand_category_hot set weights = ? where brandId = ? and categoryId = ?";
		shopDao.update(sql, new Object[] { weights, brandId, categoryId });
	}

	public void updateBrandHot(Long cid, Integer weights) {
		String sql = "update t_brand_category_hot set weights = ? where id = ?";
		shopDao.update(sql, new Object[] { weights, cid });
	}

	public void updateanncumentBrandHot(Long categoryId, Long brandId,
			Integer weights) {
		String sql = "update t_brand_annoucement set  weights = ? where brandId = ? and categoryId = ?";
		shopDao.update(sql, new Object[] { weights, brandId, categoryId });
	}

	public void saveBrandWeight(Long categoryId, Long brandId, Integer weights) {
		String sql = "delete from t_brand_category_hot where brandId = ? and categoryId = ?";
		shopDao.delete(sql, new Object[] { brandId, categoryId });
		String insertSql = "insert into t_brand_category_hot(id,brandId,categoryId,weights) values(null,?,?,?)";
		shopDao
				.update(insertSql,
						new Object[] { brandId, categoryId, weights });
	}

	public void saveanncoumentBrandWeight(Long categoryId, Long brandId,
			Integer weights) {
		String sql = "delete from t_brand_annoucement where brandId = ? and categoryId = ?";
		shopDao.delete(sql, new Object[] { brandId, categoryId });
		String insertSql = "insert into t_brand_annoucement(id,brandId,categoryId,weights) values(null,?,?,?)";
		shopDao
				.update(insertSql,
						new Object[] { brandId, categoryId, weights });
	}

	public void saveBrandCategoryWeight(Long categoryId, Long brandId,
			Long typeId, Integer weights) {
		if (-1 == typeId) {
			String sql = "delete from t_ad_category_brand where brandId = ? and categoryId = ?";
			shopDao.delete(sql, new Object[] { brandId, categoryId });
			String insertSql = "insert into t_ad_category_brand(id,brandId,categoryId,weights) values(null,?,?,?)";
			shopDao.update(insertSql, new Object[] { brandId, categoryId,
					weights });
		} else {
			String sql = "delete from t_ad_category_brand where brandId = ? and categoryId = ? and typeId = ?";
			shopDao.delete(sql, new Object[] { brandId, categoryId, typeId });
			String insertSql = "insert into t_ad_category_brand(id,brandId,categoryId,typeId,weights) values(null,?,?,?,?)";
			shopDao.update(insertSql, new Object[] { brandId, categoryId,
					typeId, weights });
		}

	}

	public PageUtil findBrand(Long categoryId, Long typeId, int page, int limit) {
		String sql = "SELECT tbg.id,tbg.name,tbg.imgsrc,tacb.weights code FROM t_g_brand tbg LEFT JOIN t_ad_category_brand tacb ON tbg.id = tacb.brandId ";
		String countSql = "SELECT count(*) FROM t_g_brand tbg LEFT JOIN t_ad_category_brand tacb ON tbg.id = tacb.brandId ";
		Long tempId = 0l;
		if (-1 == typeId||-2 == typeId) {
			sql += " where tacb.categoryId = ? ";
			countSql += " where tacb.categoryId = ? ";
			tempId = categoryId;
		} else {
			sql += " where tacb.typeId = ? ";
			countSql += " where tacb.typeId = ? ";
			tempId = typeId;
		}
		if(-2 == typeId){
			sql += " and tacb.typeId = -2 ";
			countSql += " and tacb.typeId = -2 ";
		}
		sql += " ORDER BY tacb.weights DESC limit ?,?";
		PageUtil pu = new PageUtil();
		List<TgBrand> list = shopDao.findList(sql, new Object[] { tempId,
				(page - 1) * limit, limit });
		pu.setList(list);
		pu.setPageNo(page);
		pu.setPageSize(limit);
		List<Object[]> countList = shopDao.findObjectArryList(countSql,
				new Object[] { tempId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		} else {
			pu.setTotalRecords(0);
		}
		return pu;
	}

	public void updateBrandCategoryAd(Long categoryId, Long typeId,
			Long brandId, int weights) {
		if (-1 == typeId) {
			String updatesql = "update t_ad_category_brand set weights = ? where brandId = ? and categoryId = ?";
			shopDao.update(updatesql, new Object[] { weights, brandId,
					categoryId });
		} else {
			String updatesql = "update t_ad_category_brand set weights = ? where brandId = ? and categoryId = ? and typeId = ?";
			shopDao.update(updatesql, new Object[] { weights, brandId,
					categoryId, typeId });
		}
	}

	public List<TgBrand> bulidHotTrend() {
		String sql = "SELECT tbg.id,tbg.imgsrc,tacb.categoryId categoryId FROM t_g_brand tbg LEFT JOIN t_ad_category_brand tacb ON tbg.id = tacb.brandId where tacb.categoryId = 0 ORDER BY tacb.weights DESC limit 0,3";
		return shopDao.findList(sql);
	}

	public List<TgBrand> bulidBrandAd(Long bigCategoryId) {
		String sql = "SELECT tbg.id,tbg.imgsrc,tacb.categoryId FROM "
				+ "(SELECT t.* FROM t_g_brand t WHERE EXISTS (SELECT 1 FROM t_brand_type a WHERE a.brandId = t.id AND EXISTS (SELECT 1 FROM t_g_category c WHERE a.categoryId = c.id AND c.pID = ?)))"
				+ " tbg LEFT JOIN t_ad_category_brand tacb ON tbg.id = tacb.brandId  ORDER BY tacb.weights DESC limit 0,3";
		return shopDao.findList(sql, new Object[] { bigCategoryId });
	}

	public List<TgBrand> bulidBrandAd2(Long bigCategoryId) {
		String sql = "SELECT tbg.id,tbg.imgsrc,tacb.categoryId FROM "
				+ " t_g_brand "
				+ " tbg , t_ad_category_brand tacb where tbg.id = tacb.brandId and tacb.categoryId = ?  ORDER BY tacb.weights DESC limit 0,3";
		return shopDao.findList(sql, new Object[] { bigCategoryId });
	}

	public List<TgBrand> bulidBrandAdCategory(Long categoryId) {
		String sql = "SELECT tbg.* FROM "
				+ "(SELECT t.* FROM t_g_brand t WHERE EXISTS (SELECT 1 FROM t_brand_type a WHERE a.brandId = t.id AND a.categoryId =?))"
				+ " tbg LEFT JOIN t_ad_category_brand tacb ON tbg.id = tacb.brandId  ORDER BY tacb.weights DESC limit 0,3";
		return shopDao.findList(sql, new Object[] { categoryId });
	}

	public Long findCidByBrandId(Long brandId) {
		String sql = "select categoryId from t_brand_type where brandId = ? limit 0,1";
		List<Object[]> countList = shopDao.findObjectArryList(sql,
				new Object[] { brandId });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			return new Long(countAry[0].toString());
		}
		return 10l;
	}

	public Long saveBrand(TgBrand brand) {
		return shopDao.saveEntity(brand);
	}

	public PageUtil searchByKeyWords(String keywords, int page, int limit) {
		String sql = "select DISTINCT tgb.* from t_g_brand tgb,t_pinggou tpg where tgb.id = tpg.brandId and tgb.name like '%"
				+ keywords + "%' limit ?,? ";
		String countSql = "select count(DISTINCT tgb.id) from t_g_brand tgb,t_pinggou tpg where tgb.id = tpg.brandId and tgb.name like '%"
				+ keywords + "%'";
		PageUtil pu = new PageUtil();
		List<TgBrand> list = shopDao.findList(sql, new Object[] {
				(page - 1) * limit, limit });
		pu.setList(list);
		pu.setPageNo(page);
		pu.setPageSize(limit);
		List<Object[]> countList = shopDao.findObjectArryList(countSql);
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		} else {
			pu.setTotalRecords(0);
		}
		return pu;
	}

//	public List<TgBrand> findBrandByAnnocumentCategroyId() {
//		String sql = "SELECT tgb.id,tgb.name,tgb.imgsrc,ifnull(tba.weights,0) as auding FROM t_brand_annoucement tba left join (SELECT * FROM  t_g_brand tgb1 WHERE EXISTS (SELECT 1 FROM t_pinggou tpg WHERE tgb1.id = tpg.brandId)) tgb  ON tgb.id = tba.brandId ORDER BY tba.weights DESC limit 0,30";
//		return shopDao.findList(sql);
//	}
	
	public List<TgBrand> findBrandByAnnocumentCategroyId() {
		String sql = "SELECT tgb.id,tgb.name,tgb.imgsrc,ifnull(tba.weights,0) as auding FROM t_brand_annoucement tba left join t_g_brand tgb  ON tgb.id = tba.brandId ORDER BY tba.weights DESC limit 0,30";
		return shopDao.findList(sql);
	}

	public void modifyAdIndex(Long sid, Long tid, Integer sweight,
			Integer tweight, Integer sindex, Integer tindex) {
		String sql = "update t_brand_annoucement set weights = ? where brandId = ?";
		if (sweight == 0) {
			sweight = 31 - sindex;
			TbrandAnnoucement tba = new TbrandAnnoucement();
			tba.setBrandId(sid);
			tba.setWeights(sweight);
			tbaDao.saveEntity(tba);
		} else {
			tbaDao.update(sql, new Object[] { tweight, sid });
		}
		if (tweight == 0) {
			tweight = 31 - tindex;
			TbrandAnnoucement tba = new TbrandAnnoucement();
			tba.setBrandId(tid);
			tba.setWeights(tweight);
			tbaDao.saveEntity(tba);
		} else {
			tbaDao.update(sql, new Object[] { sweight, tid });
		}
	}

	public List<TgBrand> findByKeyWord(String keyword) {
		String str = " SELECT distinct b.* FROM t_g_brand b ,t_pinggou tpg WHERE not exists (select 1 from T_brand_Annoucement tba where tba.brandId = b.id) and b.id = tpg.brandId and b.name like '%"
				+ keyword + "%'";
		return shopDao.findList(str);
	}

	public void modifyAd(Long sid, Long tid) {
		String sql = "update t_brand_annoucement set brandId = ? where brandId = ?";
		tbaDao.update(sql, new Object[] { tid, sid });
	}

	public List<TgBrand> searchPingou4IndexByKey(String keyword, Long cid) {
		String sql = "select b.id,b.name,b.imgsrc,b.companyName,tpg.id sysuserId FROM t_g_brand b,t_pinggou tpg where b.id = tpg.brandId"
				+ " and not exists (select 1 from t_pingou_index tpi where tpi.brandId = b.id and tpi.categoryId = "
				+ cid
				+ ") and b.name like '%"
				+ keyword
				+ "%' and exists (select 1 from t_g_category tgc where tgc.id = tpg.categoryId and tgc.pid = "
				+ cid + ")";
		return shopDao.findList(sql);
	}

	public void addPinggouAd(Long bid, Long pingouId, Long cid, int weight) {
		TpingouIndex tpi = new TpingouIndex();
		tpi.setBrandId(bid);
		tpi.setCategoryId(cid);
		tpi.setPingouId(pingouId);
		tpi.setWeights(weight);
		tpiDao.saveEntity(tpi);
	}

	public void modifyPingouIndex(Long sid, Long tid, Integer sweight,
			Integer tweight, Integer sindex, Integer tindex) {
		String sql = "update t_pingou_index set weights = ? where brandId = ?";
		tpiDao.update(sql, new Object[] { tweight, sid });
		tpiDao.update(sql, new Object[] { sweight, tid });
	}

	public boolean deleteFavorable(String idString) {
		boolean isFlag = true;
		if (idString == null || "".equals(idString))
			return false;
		String sql = "";
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "delete from t_g_favorable where id=" + delteid[i];
				dao.delete(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return isFlag;
	}

	public boolean audFavorable(String idString, String autding) {
		boolean isFlag = true;
		if (idString == null || "".equals(idString))
			return false;
		String sql = "";
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "update t_g_favorable set autding='" + autding
						+ "' where id=" + delteid[i];
				dao.update(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return isFlag;
	}

	public boolean deletecases(String idString) {
		boolean isFlag = true;
		if (idString == null || "".equals(idString))
			return false;
		String sql = "";
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "delete from t_g_case where id=" + delteid[i];
				dao.delete(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return isFlag;
	}

	public void changeAuding(Long brandId) {
		String sql = "update t_g_brand set auding='0' where id=?";
		dao.update(sql, new Object[] { brandId });
	}

	public void changePingouIndex(Long sid, Long tid, Long pid, Long cid) {
		String sql = "update t_pingou_index set pingouId = ?,brandId = ? where brandId = ? and categoryId = ?";
		tpiDao.update(sql, new Object[] { pid, tid, sid, cid });
	}

	public void deleteInformationAd(Long categoryId, Long brandId, Long typeId) {
		String sql = "delete from t_ad_category_brand where brandId=? and categoryId=?";
		if (-1 != typeId) {
			sql += " and typeId = " + typeId;
		}
		dao.delete(sql, new Object[] { brandId, categoryId });
	}

	public boolean checkDel(String ids) {
		if ("".equals(ids))
			return true;
		String[] delteid = ids.split("_");
		boolean flag = true;
		for (int i = 0; i < delteid.length; i++) {
			if (flag) {
				String sql = "select count(*) from t_pinggou where brandId = ?";
				if (bulidResult(sql, new Object[] { delteid[i] }) > 0)
					flag = false;
				if (!flag)
					return flag;
				String sql1 = "select count(*) from t_brand_annoucement where brandId = ?";
				if (bulidResult(sql1, new Object[] { delteid[i] }) > 0)
					flag = false;
			} else
				break;
		}
		return flag;
	}

	private int bulidResult(String sql, Object[] conditionAry) {
		int count = 0;
		List<Object[]> list = dao.findObjectArryList(sql, conditionAry);
		Object[] objAry = list.get(0);
		count = new Integer(objAry[0].toString());
		return count;
	}

//	public PageUtil findBrandByCategoryId(Long categoryId,String name,String auding, int page, int limit) {
		public PageUtil findBrand(Map<String,String>map, int page, int limit){
			String categoryId = map.get("categoryId");
			String name = map.get("name");
			String auding = map.get("auding");
			String typeId = map.get("typeId");
			String countSql = "";
			String sql = "";
			if(!"".equals(typeId)&&null!=typeId){
				if(!"".equals(categoryId)&&null!=categoryId){
					countSql = "select count(*) from t_g_brand t where exists (select 1 from t_brand_type where t.id=brandid and typeId="+typeId+" and categoryid = "+categoryId+") ";
					sql="select * from t_g_brand t where exists (select 1 from t_brand_type where t.id=brandid and typeId="+typeId+" and categoryid = "+categoryId+")";
				}else{
					countSql = "select count(*) from t_g_brand t where exists (select 1 from t_brand_type where t.id=brandid and typeId="+typeId+") ";
					sql="select * from t_g_brand t where exists (select 1 from t_brand_type where t.id=brandid and typeId="+typeId+")";
				}
			}else{
				countSql = "select count(*) from t_g_brand t where exists (select 1 from t_brand_type where t.id=brandid and categoryid = "+categoryId+") ";
				sql="select * from t_g_brand t where exists (select 1 from t_brand_type where t.id=brandid and categoryid = "+categoryId+")";
			}
			if(!"".equals(name)){
				countSql += " and name like '%"+name+"%'";
				sql += " and name like '%"+name+"%'";
			}
			if(!"".equals(auding)){
				countSql += " and auding = '"+auding+"'";
				sql += " and auding = '"+auding+"'";
			}
			PageUtil pu = new PageUtil();
			pu.setPageNo(page);
			pu.setPageSize(limit);
			List<Object[]> countList = dao.findObjectArryList(countSql);
			if (null != countList && countList.size() > 0) {
				Object[] countAry = countList.get(0);
				pu.setTotalRecords(new Integer(countAry[0].toString()));
				List<TgBrand> list = shopDao.findList(sql+" limit ?,?", new Object[] {
						(page - 1) * limit, limit });
				pu.setList(list);
			} else {
				pu.setTotalRecords(0);
			}
			return pu;
		}
}
